package com.yjb.demo.websocket.client.application;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;

/**
 * @author yjb
 * @description
 * @create 2024/9/24 9:31
 */
@Slf4j
public class WebSocketClientRunner implements Runnable{

    private final String uri;
    private final WebSocketClientDemo client;

    public WebSocketClientRunner(String uri, WebSocketClientDemo client) {
        this.uri = uri;
        this.client = client;
    }

    @Override
    public void run() {
        while (true){
            try {
                WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                URI endpointURI = new URI(uri);
                Session session = container.connectToServer(client, endpointURI);
                if (session.isOpen()){
                    return;
                }
            }catch (Exception e){
                log.error("websocket 客户端连接失败，uri = {}",uri, e);
            }
        }
    }
}
